from modelscope import Qwen2_5_VLForConditionalGeneration, AutoTokenizer, AutoProcessor
from qwen_vl_utils import process_vision_info
import time


model_id = "Qwen/Qwen2.5-VL-3B-Instruct"
# default: Load the model on the available device(s)
model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
    model_id, torch_dtype="auto", device_map="auto"
)

# We recommend enabling flash_attention_2 for better acceleration and memory saving, especially in multi-image and video scenarios.
# model = Qwen2_5_VLForConditionalGeneration.from_pretrained(
#     "Qwen/Qwen2.5-VL-3B-Instruct",
#     torch_dtype=torch.bfloat16,
#     attn_implementation="flash_attention_2",
#     device_map="auto",
# )

# default processer
processor = AutoProcessor.from_pretrained(model_id)

# The default range for the number of visual tokens per image in the model is 4-16384.
# You can set min_pixels and max_pixels according to your needs, such as a token range of 256-1280, to balance performance and cost.
# min_pixels = 256*28*28
# max_pixels = 1280*28*28
# processor = AutoProcessor.from_pretrained(model_id, min_pixels=min_pixels, max_pixels=max_pixels)

image_path = "output_image.png"  # 替换为你的截图路径
messages = [
    {
        "role": "system",
        "content": [{
            "type":"text",
            "text":'''我正在玩一款名为"KitTechMatch3D"的游戏，这是一款经典的消除类游戏。游戏中有以下特点和规则:
        1.关卡的上方规定了要手机的物品种类和数量，在规定时间内收集完成后即可胜利。
        2.玩家需要使用鼠标点击来收集物品，收集的物品会出现在放置栏。
        3. 3个相同的物品在放置栏可以消除，如果放置栏满了，游戏会失败，当目标物体全部被消除后，游戏就会成功
        现在你是一个玩这种游戏的高手，你需要帮助玩家在尽可能短的时间内完成游戏目标的收集。根据游戏截图（截图里有一个个的格子，并带有编号），你需要给玩家建议点击哪个格子。
        '''
    }]
    },
    {
        "role": "user",
        "content": [
            {
                "type": "image",
                "image": image_path
            },
            {
                "type": "text",
                "text": "我现在应该点击哪个格子。只需要回答点击的格子的位置(行，列)和物品名字。"
            }
        ]
    }
]

time_start = time.time()
# Preparation for inference
text = processor.apply_chat_template(
    messages, tokenize=False, add_generation_prompt=True
)
image_inputs, video_inputs = process_vision_info(messages)
inputs = processor(
    text=[text],
    images=image_inputs,
    videos=video_inputs,
    padding=True,
    return_tensors="pt",
)
inputs = inputs.to("cuda")

# Inference: Generation of the output
generated_ids = model.generate(**inputs, max_new_tokens=128)
generated_ids_trimmed = [
    out_ids[len(in_ids) :] for in_ids, out_ids in zip(inputs.input_ids, generated_ids)
]
output_text = processor.batch_decode(
    generated_ids_trimmed, skip_special_tokens=True, clean_up_tokenization_spaces=False
)
print(f"predict cost time: {time.time() - time_start}s")
print(output_text)